package com.sinsz.pay.util;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * @author chenjianbo
 */
public final class MD5Utils {

    public static String MD5(final String s) {
        final byte[] btInput = s.getBytes();
        return MD5Utils.MD5(btInput);
    }

    public static String MD5(final String s, final String charset)
            throws Exception {
        final byte[] btInput = s.getBytes(charset);
        return MD5Utils.MD5(btInput);
    }

    private static String MD5(final byte[] btInput) {
        final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            final MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            // 获得密文
            final byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            final int j = md.length;
            final char[] str = new char[j * 2];
            int k = 0;
            for (final byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (final Exception e) {
            e.printStackTrace(System.out);
            return null;
        }
    }

    public static String getFileMD5(final File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        final byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (final Exception e) {
            e.printStackTrace(System.out);
            return null;
        }
        final BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

}
